package com.why.utils;

import java.nio.ByteBuffer;

/**
 * @author by xiaoTian
 * @date 2022/5/20.
 * 将byte[]转换为各种基本类型
 */
public class BaseConversionUtils {

    public static short byte2short(byte[] b){
        short l = 0;
        for (int i = 0; i < 2; i++) {
            l<<=8;
            l |= (b[i] & 0xff);
        }
        return l;
    }


    public static byte[] short2byte(short s){
        byte[] b = new byte[2];
        for(int i = 0; i < 2; i++){
            int offset = 16 - (i+1)*8; //因为byte占4个字节，所以要计算偏移量
            b[i] = (byte)((s >> offset)&0xff); //把16位分为2个8位进行分别存储
        }
        return b;
    }


    public static byte[] int2byte(int s){
        byte[] b = new byte[2];
        for(int i = 0; i < 4; i++){
            int offset = 16 - (i+1)*8; //因为byte占4个字节，所以要计算偏移量
            b[i] = (byte)((s >> offset)&0xff); //把32位分为4个8位进行分别存储
        }
        return b;
    }


    public static int byte2int(byte[] b){
        int l = 0;
        for (int i = 0; i < 4; i++) {
            l<<=8; //<<=和我们的 +=是一样的，意思就是 l = l << 8
            l |= (b[i] & 0xff); //和上面也是一样的  l = l | (b[i]&0xff)
        }
        return l;
    }

    public static long byte2long(byte[] b){
        long l = 0;
        for (int i = 0; i < 8; i++) {
            l <<= 8;
            l |= b[i] & 0xFF;
        }
        return l;
    }

    public static double byte2Double(byte[] arr) {
        long value = 0;
        for (int i = 0; i < 8; i++) {
            value |= ((long) (arr[i] & 0xff)) << (8 * i);
        }
        return Double.longBitsToDouble(value);
    }

    /**
     * 转换byte数组为int（大端）
     * @return
     * @note 数组长度至少为4，按小端方式转换，即传入的bytes是大端的，按这个规律组织成int
     */
    public int Bytes2Int_BE(byte[] bytes) {
        if (bytes.length < 4)
            return -1;
        int iRst = (bytes[0] << 24) & 0xFF;
        iRst |= (bytes[1] << 16) & 0xFF;
        iRst |= (bytes[2] << 8) & 0xFF;
        iRst |= bytes[3] & 0xFF;

        return iRst;
    }



}
